import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import { Dispatch } from 'redux';

import router from 'umi/router';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Radio,
  Button,
} from 'antd';

import '@ant-design/compatible/assets/index.css';
import { DetailInfoItem } from './data';

const { Option } = Select;
const { RangePicker } = DatePicker;
const { Item } = Form;
interface PackagePricesAddProps extends FormComponentProps {
  dispatch: Dispatch;
  detailInfo: DetailInfoItem;
  INITINFO: any;
  location: {
    query?: any;
  };
}

@connect(({
  packagePricesAdd: { detailInfo },
  common: { INITINFO },
}: any) => ({
  detailInfo,
  INITINFO,
}))

class PackagePricesAddElem extends Component<PackagePricesAddProps> {
  componentDidMount() {
    const {
      location: { query: { id, type } },
    } = this.props;
    if (id && type) this.fetchDetailInfo(id);

    this.fetchAction('common/fetchLogisList');
    this.fetchAction('common/fetchExpressList');
  }

  componentDidUpdate(props: any) {
    const {
      location: { query: { id, type } },
    } = this.props;
    if (id && type && (id !== props.location.query.id || type !== props.location.query.type)) {
      this.fetchDetailInfo(id);
    }
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  fetchDetailInfo = (id: number) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'packagePricesAdd/fetch',
      payload: { id },
    });
  };

  handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFieldsAndScroll } } = this.props;
    validateFieldsAndScroll((errors, values) => {
      if (errors) return;

      const { momentDate } = values;
      const params = {
        ...values,
        startTime: momentDate ? `${moment(momentDate[0]).format('YYYY-MM-DD')} 00:00:00` : '',
        endTime: momentDate ? `${moment(momentDate[1]).format('YYYY-MM-DD')} 00:00:00` : '',
      };
      delete params.momentDate;

      const { location: { query } } = this.props;
      if (query && query.type === '1') params.id = query.id;
      this.fetchAction('saveOrUpdate', params);
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `packagePricesAdd/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const {
      form: { getFieldDecorator },
      detailInfo,
      INITINFO: { logisList, expressList },
      location: { query },
    } = this.props;

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} title="编辑派件资费配置">
          <Form
            hideRequiredMark
            className="tableListForm"
            onSubmit={this.handleSubmit}
          >
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="物流中心" colon={false}>
                  {getFieldDecorator('logisId', {
                    initialValue: detailInfo.logisId,
                    rules: [{ required: true, message: '请选择物流中心' }],
                  })(
                    <Select
                      showSearch
                      placeholder="请选择"
                      disabled={Boolean(detailInfo.logisId && query && query.type === 1)}
                      filterOption={(input: any, option: any) => option.props.children
                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {logisList.map((item: any) => (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="合同编号" colon={false}>
                  {getFieldDecorator('contractCode', {
                    initialValue: detailInfo.contractCode,
                    rules: [{ required: true, message: '请输入合同编号' }],
                  })(<Input allowClear placeholder="请输入" />)}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="快递公司" colon={false}>
                  {getFieldDecorator('expressId', {
                    initialValue:
                      query && query.type === '1' && detailInfo.expressId
                        ? detailInfo.expressId
                        : '',
                    rules: [{ required: true, message: '请选择快递公司' }],
                  })(
                    <Select
                      showSearch
                      placeholder="请选择"
                      disabled={Boolean(detailInfo.expressId && query && query.type === 1)}
                      filterOption={(input: any, option: any) => option.props.children
                        .toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {expressList.map((item: any) => (
                        <Option value={item.id} key={item.id}>
                          {item.name}
                        </Option>
                      ))}
                    </Select>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Item label="起止日期" colon={false}>
                  {getFieldDecorator('momentDate', {
                    initialValue: [moment(detailInfo.startTime), moment(detailInfo.endTime)],
                    rules: [{ required: true, message: '请选择起止日期' }],
                  })(
                    <RangePicker style={{ width: '100%' }} />,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="计费标准" colon={false}>
                  {getFieldDecorator('chargeType', {
                    initialValue: detailInfo.chargeType,
                    rules: [{ required: true, message: '请选择计费标准' }],
                  })(
                    <Radio.Group>
                      <Radio value={1}>接驳计费</Radio>
                      <Radio value={2}>签收计费</Radio>
                    </Radio.Group>,
                  )}
                </Item>
              </Col>
              <Col md={8} sm={24}>
                <Item label="结算方式" colon={false}>
                  {getFieldDecorator('settleWay', {
                    initialValue: detailInfo.settleWay,
                    rules: [{ required: true, message: '请选择结算方式' }],
                  })(
                    <Radio.Group>
                      <Radio value={1}>月结月清</Radio>
                      <Radio value={2}>日结日清</Radio>
                    </Radio.Group>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24} style={{ display: 'flex' }}>
                <Item label="计费单价" colon={false} style={{ flex: 1 }}>
                  {getFieldDecorator('unitPrice', {
                    initialValue: detailInfo.unitPrice,
                    rules: [{ required: true, message: '请输入计费单价' }],
                  })(<InputNumber placeholder="请输入" min={0} style={{ width: '100%' }} />)}
                </Item>
                <span className="marginL16" style={{ lineHeight: '32px' }}>
                  分
                </span>
              </Col>
              <Col md={8} sm={24}>
                <Item label="校外派件" colon={false}>
                  {getFieldDecorator('isOutSchool', {
                    initialValue: detailInfo.isOutSchool,
                    rules: [{ required: true, message: '请选择是否校外派件' }],
                  })(
                    <Radio.Group>
                      <Radio value={0}>否</Radio>
                      <Radio value={1}>是</Radio>
                    </Radio.Group>,
                  )}
                </Item>
              </Col>
            </Row>
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Button
                type="primary"
                htmlType="submit"
              >
                保存
              </Button>
              <Button
                ghost
                type="primary"
                className="marginL16"
                onClick={() => router.goBack()}
              >
                取消
              </Button>
            </Row>
          </Form>
        </Card>
      </Fragment>
    );
  }
}

export default Form.create<PackagePricesAddProps>()(PackagePricesAddElem);
